package com.lx.base.config.converter;

import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.util.TimeZone;

/**
 * 解决前端往后端传时间参数时出现的格式问题
 * @author lixing
 * @date 2022/6/29 13:45
 */
@Configuration
public class DateConverterConfig {
    @Bean
    DateJacksonConverter dateJacksonConverter(){
        return new DateJacksonConverter();
    }
    @Bean
    LocalDateTimeJacksonConverter localDateTimeJacksonConverter(){
        return new LocalDateTimeJacksonConverter();
    }
    @Bean
    LocalDateJacksonConverter localDateJacksonConverter(){
        return new LocalDateJacksonConverter();
    }
    @Bean
    LocalTimeJacksonConverter localTimeJacksonConverter(){
        return new LocalTimeJacksonConverter();
    }

    @Bean
    @Primary
    public Jackson2ObjectMapperFactoryBean jackson2ObjectMapperFactoryBean(
            @Autowired DateJacksonConverter dateJacksonConverter,
            @Autowired LocalDateTimeJacksonConverter localDateTimeJacksonConverter,
            @Autowired  LocalDateJacksonConverter localDateJacksonConverter,
            @Autowired LocalTimeJacksonConverter localTimeJacksonConverter
    ) {
        Jackson2ObjectMapperFactoryBean jackson2ObjectMapperFactoryBean = new Jackson2ObjectMapperFactoryBean();
        TimeZone  timeZone=TimeZone.getTimeZone("Asia/Shanghai");
        jackson2ObjectMapperFactoryBean.setTimeZone(timeZone);
        JsonDeserializer[] jsonDeserializers=new JsonDeserializer[]{dateJacksonConverter,localDateTimeJacksonConverter,localDateJacksonConverter,localTimeJacksonConverter};

        jackson2ObjectMapperFactoryBean.setDeserializers(jsonDeserializers);
        return jackson2ObjectMapperFactoryBean;
    }

    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(
            @Autowired ObjectMapper objectMapper) {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter =
                new MappingJackson2HttpMessageConverter();
        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
        return mappingJackson2HttpMessageConverter;
    }
}
